import { getListApi, exportExcelApi } from "@/api/reportManager/grossProfitManagement/";
import { message } from "ant-design-vue";
import { computed } from "vue";
export default function OperationHook(state: Base.GeneraDataType) {
  const { searchForm, tableData, loading, tableRef, footerText } = state;
  const selectRows = computed(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const getData = () => {
    const params = {
      ...getParmas(),
      checkingStatus: 2
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        const { records, total } = data.page;
        if (code === 200) {
          tableData.value = records || [];
          searchForm.total = Number(total);
          footerText.value = data.statistics || "";
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const getParmas = () => {
    const { waybillNums, accountPeriodIdList, customerIdList, channelIdList, pageNum, pageSize, total, driverUserIdList } = searchForm;

    const params: Parameters<typeof getListApi>[0] = {
      channelIdList,
      customerIdList,
      accountPeriodIdList,
      waybillNums: [],
      pageNum,
      pageSize,
      total,

      driverUserIdList
    };
    if (waybillNums)
      params.waybillNums = waybillNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");

    if (channelIdList.length) {
      params.channelIdList = channelIdList.map((t: any) => t[t.length - 1]);
    }

    return params;
  };

  const searchHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };

  //批量导出
  const exportExcelHandle = () => {
    return exportExcelApi({ ...getParmas(), list: selectRows.value }).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
        getData();
      }
    });
  };

  return {
    searchHandle,
    getData,
    exportExcelHandle
  };
}
